﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace SynoManager.DownloadStation.Plugins
{
    [DownloadStationPlugin("Credential Manager", "Automatically add your credentials to URLs", "Grad \"Flard\" van Horck", "1.0")]
    public class CredentialManager : IDownloadUrlHandlerPlugin, IDownloadStationPreferencePanelPlugin
    {
        private DownloadStationService service;

        public void Initialize(DownloadStationService service)
        {
            this.service = service;
            Load();
        }

        public void Close()
        {
            Save();
        }

        private Dictionary<string, SiteCredential> credentials = new Dictionary<string, SiteCredential>();

        public IEnumerable<SiteCredential> Credentials
        {
            get { return credentials.Values; }
        }

        public void Add(SiteCredential credential)
        {
            credentials.Add(credential.Host, credential);
        }

        public void Remove(SiteCredential credential)
        {
            credentials.Remove(credential.Host);
        }

        private LocalSiteCredentialStore store = new LocalSiteCredentialStore();
        public void Load()
        {
            credentials.Clear();
            foreach(var cred in store.Load())
            {
                credentials.Add(cred.Host, cred);
            }
        }

        public void Save()
        {
            List<SiteCredential> list = new List<SiteCredential>();
            foreach(var cred in credentials.Values)
            {
                list.Add(cred);
            }
            store.Save(list.ToArray());
        }

        public void Process(ProcessUrlArgs args)
        {
            string host = args.Url.Host;
            if (credentials.ContainsKey(host))
            {
                if (String.IsNullOrEmpty(args.Url.UserInfo))
                {
                    SiteCredential credential = credentials[host];
                    string url = args.Url.ToString();
                    url = url.Replace(host, credential.Username + ":" + credential.Password + "@" + host);
                    Debug.WriteLine("Added credentials for user " + credential.Username + " @ " + host);
                    args.Url = new Uri(url);
                }
            }
        }

        #region IDownloadStationPreferencePanelPlugin Members

        public SynoManager.GUI.PreferencesPanel PreferencePanel
        {
            get { return new CredentialManagerPanel(this); }
        }

        public string PreferenceNodeText
        {
            get { return "Credential Manager"; }
        }

        public System.Drawing.Image PreferenceNodeImage
        {
            get { return Properties.Resources.key; }
        }

        #endregion
    }
}
